<template>
  <div>
    <el-dialog
      :model-value="open"
      :close-on-click-modal="false"
      :title="title"
      append-to-body
      :before-close="handleClose"
    >
      <el-form
        ref="editForm"
        :model="form"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="岗位名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入岗位名称"></el-input>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入权限字符"></el-input>
        </el-form-item>
        <el-form-item label="岗位顺序" prop="roleSort">
          <el-input-number
            v-model="form.roleSort"
            controls-position="right"
            :min="0"
            type="number"
            width="100px"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dicts[DictDirection.是否禁用字典]" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="form.menuCheckStrictly">父子联动</el-checkbox>
          <el-tree
            ref="menu"
            :data="menuOptions"
            show-checkbox
            class="tree_border"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import type { ElTree } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import { treeselect, roleMenuTreeselect } from '@/api/system/menu'
import { listRole, updateRole, addRole, getRole } from '@/api/system/role'

const dicts = useDicts()
dicts.setDicts(DictDirection.是否禁用字典)
const props = defineProps({
  open: {
    type: Boolean,
  },
  title: {
    type: String,
    default: '新增岗位',
  },

})
const emit = defineEmits(['changeList', 'update:open', 'update:title'])
// 表单参数
const form = ref({
    roleId: undefined,
    roleName: undefined,
    roleKey: undefined,
    roleSort: 0,
    status: undefined,
    remark: undefined,
    menuIds: [],
    deptCheckStrictly: true,
    menuCheckStrictly: true,
  }),
  defaultProps = {
    children: 'children',
    label: 'label',
  },

  menu = ref<InstanceType<typeof ElTree>>(),
  rules = {
    roleName: [{ required: true, message: '岗位名称不能为空', trigger: 'blur' }],
    roleKey: [{ required: true, message: '权限字符不能为空', trigger: 'blur' }],
    roleSort: [
      {
        required: true,
        message: '岗位顺序不能为空',
        trigger: 'blur',
      },
      {
        validator: (rule, value, callback) => {
          if (!(/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value)) {
            callback(new Error('请输入数字值'))
          } else {
            callback()
          }
        },
      },
    ],
  },
  // 新增修改表单
  editForm = ref(undefined),
  {
    proxy,
  }:{
    proxy:any
  } = getCurrentInstance()
const menuOptions = ref([])
// 新增菜单权限
const getMenuTreeselect = () => {
  treeselect().then((res) => {
    menuOptions.value = res.data
  })
}
const handleChange = (value) => {
  console.log(value, '1232')
}
getMenuTreeselect()
// 重置新增修改列表
const reset = () => {
  if (menu.value != null) {
    menu.value.setCheckedKeys([])
  }
  form.value = {
    roleId: undefined,
    roleName: undefined,
    roleKey: undefined,
    roleSort: 0,
    status: undefined,
    remark: undefined,
    menuIds: [],
    deptCheckStrictly: true,
    menuCheckStrictly: true,
  }
  proxy.$resetForm(editForm.value)
}

// 新增修改——确定
const submitForm = () => {
  proxy.$validateForm(editForm.value, () => {
    form.value.menuIds = getMenuAllCheckedKeys()
    if (form.value.roleId != undefined) {
      console.log(form.value.roleId)
      updateRole(form.value).then(res => {
        if (res.code == 200) {
          reset()
          emit('update:open', false)
          ElMessage.success('修改成功')
          emit('changeList')
        }
      })
    } else {
      addRole(form.value).then(res => {
        if (res.code == 200) {
          reset()
          emit('update:open', false)
          ElMessage.success('新增成功')
          emit('changeList')
        }
      })
    }
  })
}
// 获取菜单权限选中
const getMenuAllCheckedKeys = () => {
  //	若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组
  const checkedKeys = proxy.$refs.menu.getHalfCheckedKeys()
  //  若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组
  const halfCheckedKeys = proxy.$refs.menu.getCheckedKeys()
  // eslint-disable-next-line prefer-spread
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  return checkedKeys 
}
// getMenuAllCheckedKeys()
// 修改新增——取消
const cancel = () => {
  emit('update:open', false)
}
// const getList = (id) => {
//   getPost(id)
//   .then((res) => {
//     if (res.code === 200) {
//       const resList = JSON.parse(JSON.stringify(res.data))
//       form.value = resList
//     } else {
//       ElMessage.error(res.msg)
//     }
//   })
//   .catch((err) => {
//     console.log(err)
//     ElMessage.error(err)
//   })
// }
// const getRoleMenuTreeselect = (id) => roleMenuTreeselect(id).then(res => {
//   const menusList = JSON.parse(JSON.stringify(res.data.menus))
//   menuOptions = menusList
//   console.log(menuOptions)
// }) 
const getRoleMenuTreeselect = (id) => roleMenuTreeselect(id).then(res => {
  menuOptions.value = res.data.menus
  return res
})
const handleClose = () => {
  reset()
  emit('update:open', false)
}
 
// 查询岗位
// const getList = (id) => {
//   getRole(id).then((res) => {
//     console.log(res)
//     form.value = res.data
//     open.value = true
//     proxy.$nextTick(() => {
//       getRoleMenuTreeselect(props.roleIdRef)
//       .then(res => { proxy.$refs.menu.setCheckedKeys(res.checkedKeys) })
//     })
//   })
// }

defineExpose({
  // getList,
  getMenuTreeselect,
  getRoleMenuTreeselect,
  menu,
  form,
})
</script>

<style lang="less" scoped>
.tree_border {
  border: 0 solid #ccc;
  border-radius: 5px;
}
/deep/.el-form-item__content {
  display: inline-block;
}
</style>
